//获取截断的目标页面路径  isReset=true是返回地址并重置记录的地址 否则只返回地址
export const getTargetUrl = (isReset = false) => {
	let tmp = getApp().targetUrl
	if (isReset === true) {
		setTargetUrl();
	}
	return tmp;
}
//设置截断的目标页面路径  url不传时 重置记录的地址
export const setTargetUrl = (url = null) => {
	getApp().targetUrl = url
}
//是否登录
export const isLogin = () => {

	return wx.getStorageSync('token') ? true : false;
}

//获取用户登录凭证
export const getWxLoginCode = () => {
	return new Promise((resolve, reject) => {
		wx.login({
			success(res) {
				if (res.code) {
					//发起网络请求
					resolve(res.code);

				} else {
					modelToast({
						content: '登录失败' + res.errMsg
					});
				}
			},
			fail: () => {
				reject();
			}
		})
	})
}
//获取用户信息
export const getUserProfile = (options) => {
	return new Promise((resolve, reject) => {
		wx.getUserProfile({
			...options,
			// desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				resolve(res);
			},
			fail(err) {
				reject(err)
			}
		})
	})

}
//授权登录
export const wxAuthLogin = (options) => {
	return new Promise((resolve, reject) => {
		Promise.all([getWxLoginCode(), getUserProfile(options)]).then((resList) => {
			let [code, res] = resList
			resolve({
				code,
				encryptedData: res.encryptedData,
				iv: res.iv
			});

		}).catch((err) => {
			reject(err);
		})
	})

}
//登录成功之后跳转
export const toLinkAfterLogin = () => {
	if (getTargetUrl()) {
		return wx.redirectTo({
			url: getTargetUrl(true)
		});

	}
	wx.navigateBack({
		delta: 1,
	})
}
//执行登录、绑定手机号流程
export const auth = async (callback) => {

	//没有注册登录执行注册登录
	if (!isLogin()) {
		wx.navigateTo({
			url: '/pages/login/login',
		})
		return;
	}



	//兼容处理非跳转类功能的授权完成的后序操作
	callback && callback();
}
//判断页面权限
export const authCheck = (to = '') => {
	to = 'pages/' + to + '/' + to;
	let noAuth = [
		'pages/index/index'
	];

	if (isLogin() || (to && noAuth.indexOf(to) !== -1)) {
		return true;
	}
	return false;
}
//跳转
export const toLink = async (name, params, type = false) => {
	var url = '../' + name + '/' + name + '?';
	for (var key in params) {
		url = url + key + '=' + params[key] + '&';
	}

	if (!authCheck(name)) {

		setTargetUrl(url);
		return auth();
	}

	if (type === true) {
		wx.reLaunch({
			'url': url
		})
		return false;
	}
	wx.navigateTo({
		'url': url
	});
};
